package com.ffggffgfv.backend.controller;

import com.ffggffgfv.backend.dto.BatchRestockDTO;
import com.ffggffgfv.backend.entity.Shelf;
import com.ffggffgfv.backend.service.ShelfProductService;
import com.ffggffgfv.backend.service.ShelfService;
import com.ffggffgfv.backend.util.JWTUtil;
import com.ffggffgfv.backend.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 货架商品控制器
 */
@RestController
@RequestMapping("/api/shelves")
public class ShelfProductController {

    @Autowired
    private ShelfService shelfService;

    @Autowired
    private ShelfProductService shelfProductService;

    @Autowired
    private JWTUtil jwtUtil;

    /**
     * 批量补货操作
     *
     * @param shelfId         货架ID
     * @param batchRestockDTO 批量补货信息
     * @param token           JWT令牌
     * @return 操作结果
     */
    @PostMapping("/{shelfId}/restock/batch")
    public Result batchRestock(
            @PathVariable Long shelfId,
            @RequestBody BatchRestockDTO batchRestockDTO,
            @RequestHeader(value = "Authorization") String token) {

        Shelf existingShelf = shelfService.findById(shelfId);
        if (existingShelf == null) {
            return Result.validateFailed("货架不存在");
        }

        // 验证权限
        if (token != null && token.startsWith("Bearer ")) {
            Long merchantId = extractMerchantId(token.substring(7));
            if (merchantId != null) {
                // 如果是普通商家，只能操作自己的货架
                if (!isAdminRole(token.substring(7)) && !merchantId.equals(existingShelf.getMerchantId())) {
                    return Result.unauthorized("无权操作该货架");
                }

                // 设置操作人信息
                if (batchRestockDTO.getOperatorId() == null) {
                    batchRestockDTO.setOperatorId(merchantId);
                }
                if (batchRestockDTO.getOperatorType() == null) {
                    batchRestockDTO.setOperatorType(3); // 假设3代表商家
                }
            } else {
                return Result.unauthorized("无效的令牌");
            }
        } else {
            return Result.unauthorized("未提供令牌");
        }

        // 参数校验
        if (batchRestockDTO.getItems() == null || batchRestockDTO.getItems().isEmpty()) {
            return Result.validateFailed("补货项不能为空");
        }

        try {
            Map<String, Object> result = shelfProductService.batchRestock(shelfId, batchRestockDTO);
            return Result.success(result, "批量补货成功");
        } catch (Exception e) {
            return Result.failed("批量补货失败：" + e.getMessage());
        }
    }

    /**
     * 从令牌中提取商家ID
     *
     * @param token JWT令牌
     * @return 商家ID
     */
    private Long extractMerchantId(String token) {
        try {
            // 从令牌中解析商家ID
            return jwtUtil.extractUserId(token);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 判断是否为管理员角色
     *
     * @param token JWT令牌
     * @return 是否为管理员
     */
    private boolean isAdminRole(String token) {
        try {
            // 从令牌中解析角色
            return jwtUtil.hasAdminRole(token);
        } catch (Exception e) {
            return false;
        }
    }
}
